package cn.com.ry.framework.linklog.context;

import com.alibaba.fastjson.JSON;
import cn.com.ry.framework.linklog.constant.LinkLogPattern;

/**
 * linkLog的日志标签生成器
 */
public class LinkLogLabelGenerator {

    public static String labelPattern = "$spanId-$traceId";

    public static String generateLinkLogLabel(String preApp, String preHost, String preIp, String traceId, String spanId) {
        if (preApp == null) {
            preApp = "";
        }
        if (preHost == null) {
            preHost = "";
        }
        if (preIp == null) {
            preIp = "";
        }
        if (traceId == null) {
            traceId = "";
        }
        if (spanId == null) {
            spanId = "";
        }

        //判断是否启用kafkaJson
        String kafkaJson = System.getProperty("linklog.kafka.json");
        if (kafkaJson != null && kafkaJson.equalsIgnoreCase("kafkajson")) {
            LinkLogPattern linkLogPattern = new LinkLogPattern(traceId, spanId, preApp, preHost, preIp);
            return JSON.toJSONString(linkLogPattern);

        }
        return labelPattern.replace("$preApp", preApp)
                .replace("$preHost", preHost)
                .replace("$preIp", preIp)
                .replace("$traceId", traceId)
                .replace("$spanId", spanId);
    }

    public static String getLabelPattern() {
        return labelPattern;
    }

    public static void setLabelPattern(String labelPattern) {
        LinkLogLabelGenerator.labelPattern = labelPattern;
    }
}
